﻿Partial Public Class ScriptExecutorWindow

    'Private _scripts As IEnumerable(Of Script)
    Private _connectionString As String
    Private _scriptProject As ScriptProject
    Private _scriptExecutor As ScriptExecutor

    Private _isCancelled As Boolean = False

    Private _executedCount As Integer = 0
    Private _errorCount As Integer = 0

    ''' <summary>
    ''' Creates a new instance of the script executor window
    ''' </summary>
    ''' <param name="scripts"></param>
    ''' <param name="connectionString"></param>
    ''' <remarks></remarks>
    Public Sub New(ByVal scriptProject As ScriptProject, _
                   ByVal scripts As IEnumerable(Of Script), _
                   ByVal connectionString As String)

        ' This call is required by the Windows Form Designer.
        InitializeComponent()

        If scriptProject Is Nothing Then Throw New ArgumentNullException("scriptProject")
        If scripts Is Nothing Then Throw New ArgumentNullException("scripts")
        If String.IsNullOrEmpty(connectionString) Then Throw New ArgumentException("connectionString is null or empty.", "connectionString")

        ' Add any initialization after the InitializeComponent() call.
        _scriptProject = scriptProject
        _connectionString = connectionString

        'RQ: We don't really have a reason to save this right now, so I'm taking it out.
        '_scripts = scripts


        'Create the script executor
        _scriptExecutor = New ScriptExecutor(_scriptProject, scripts, _connectionString)

        'Set the status text
        tbStatus.Text = "Running..."

        'Show the in progress images
        BuildInProgressImage.Visibility = System.Windows.Visibility.Visible

        DoWork()
    End Sub

    ''' <summary>
    ''' Hides all of the progres images
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub HideProgressImages()
        BuildInProgressImage.Visibility = System.Windows.Visibility.Collapsed
        BuildFailedImage.Visibility = System.Windows.Visibility.Collapsed
        BuildCompletedImage.Visibility = System.Windows.Visibility.Collapsed
    End Sub

    ''' <summary>
    ''' Executes the next script and schedules itself to be run by the dispatcher when done.
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub DoWork()

        'Check for the terminating condition.  This shouldn't happen - it's just
        '  some defensive (paranoid?) code.
        If _scriptExecutor Is Nothing OrElse _scriptExecutor.Current Is Nothing Then
            Return
        End If

        'Execute the curent script
        Dim result As ScriptExecutionResult = _scriptExecutor.Execute()

        _executedCount += 1

        If Not result.Successful Then
            _errorCount += 1
        End If

        'Log the result
        LogText.Text &= " ---- " & result.ScriptItem.Name & " ----" & _
              Environment.NewLine & _
              result.ResultText & _
              Environment.NewLine

        'Make sure that the last item is visible
        LogText.ScrollToEnd()

        'This is the last one - ditch the executor.
        If _scriptExecutor.Current Is Nothing Or _isCancelled Then

            HideProgressImages()

            'Ditch the executor.  We're done with it.
            _scriptExecutor.Dispose()
            _scriptExecutor = Nothing

            If _isCancelled Then
                'We're done - let the user know.
                tbStatus.Text = "Cancelled"

                'Show the failed image for this one
                BuildFailedImage.Visibility = System.Windows.Visibility.Visible

            Else

                'Check to see if there were errors.
                If _errorCount > 0 Then

                    'We're done - let the user know.
                    tbStatus.Text = String.Format("Done, with {0} errors.", _errorCount)

                    'Show the completed image
                    BuildFailedImage.Visibility = System.Windows.Visibility.Visible

                Else

                    'We're done - let the user know.
                    tbStatus.Text = "Done"

                    'Show the completed image
                    BuildCompletedImage.Visibility = System.Windows.Visibility.Visible

                End If
                
            End If

            CancelButton.IsEnabled = False

        Else
            'There are more scripts left to be run.  Tell the dispatcher to schedule the script to be run.
            Dispatcher.BeginInvoke(New System.Threading.ThreadStart(AddressOf DoWork), System.Windows.Threading.DispatcherPriority.Background, New Object() {})
        End If

    End Sub

    Private Sub Window1_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded

        'TODO: Add a cancel operation.

    End Sub

    Private Sub CancelButton_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Try
            _isCancelled = True
            CancelButton.IsEnabled = False
        Catch ex As Exception
            ex.Handle()
        End Try
    End Sub
End Class
